let express = require('express');
const {markedFetchYoudaoLijuMainMapEntryCollectionDAO} = require("../collectionDao/markedFetchYoudaoLijuMainMapEntryCollectionDAO");
const {ObjectId} = require("mongodb");
const {latestMarkedVersionsDao} = require("../collectionDao/latestMarkedVersionsDao");
const prettier = require('prettier');

let router = express.Router();

/* GET users listing. */
router.get('/', function (req, res, next) {
    res.send('respond with a resource');
});

router.post('/codeMirror/prettier/format', function (req, res, next) {
    const jsonData = req.body;
    console.log("jsonData:",jsonData);

    const htmlContent = `<p>sdafjksafads</p> <ul> <li>dfdalkfkdas</li> <li>sdflajdsafkjk</li> <li>dsfsadf</li> </ul> <hr /> <div class="space-y-2"> <div class="space-y-2"> <section class="prose-lg max-w-none py-1"> <div class="-mb-4"> <h1 class="inline !mb-1 scroll-m-16 text-3xl font-bold">merge</h1> <div class="pl-2 flex-1 text-textSecondary text-xl font-serif"> (v.) </div> <span id="#14670" class="scroll-m-16 text-3xl font-bold flex items-center" ></span> </div> <section class=""> <p> 1630年代，&ldquo;沉没或陷入&rdquo;（某物中），这个意义现已过时，源自拉丁语&nbsp; <em class="foreign notranslate">mergere</em> &nbsp;&ldquo; <strong>浸泡，浸入</strong> ，沉浸&rdquo;，可能是从&nbsp; <em class="foreign notranslate">*mezgo</em> &nbsp;转音而来，源自 PIE&nbsp; <em class="foreign notranslate">*mezgo-</em> &nbsp;&ldquo;浸泡，沉没，洗涤，投入&rdquo;（源头还包括梵文&nbsp; <em class="foreign notranslate">majjanti</em> &nbsp;&ldquo;沉没，潜入&rdquo;，立陶宛语&nbsp; <em class="foreign notranslate">mazgoju, mazgoti,</em> ，拉脱维亚语&nbsp; <em class="foreign notranslate">mazgat</em> &nbsp;&ldquo;洗涤&rdquo;）。 </p> <p> 不及物动词意为&ldquo;沉没或消失于其他事物中，被 <strong>吞噬，失去身份</strong> &rdquo;，始见于1726年，特指法律上的&ldquo; <strong>将财产、合同等吸收到另一个中</strong> &rdquo;。及物动词&ldquo;使被吸收或消失于其他事物中&rdquo;的意义始见于1728年。相关词汇：&nbsp; <em class="foreign notranslate">Merged</em> ；&nbsp; <em class="foreign notranslate">merging</em> 。名词用法始见于1805年。 </p> </section> <div class="-mt-4"> <p class="text-sm caret-gray-400 flex items-center"> 同样来自于: <a class="ml-1 pl-1 mt-1 flex items-center no-underline" href="https://www.etymonline.com/search?sort=a&amp;q=from%3A1630s" rel="nofollow" > 1630s </a> </p> </div> </section> </div> </div> <div class="space-y-2"><hr /></div> <div class="space-y-2"> <h1 class="word__name--TTbAA" title="Origin and meaning of wash"> wash&nbsp;(v.) </h1> <section class="word__defination--2q7ZH"> <p> Old English&nbsp; <span class="foreign notranslate">wascan</span> &nbsp;"to <strong>wash, cleanse, bathe</strong> ," transitive sense in late Old English, from Proto-Germanic&nbsp; <span class="foreign notranslate">*watskan</span> &nbsp;"to wash" (source also of Old Norse&nbsp; <span class="foreign notranslate">vaska</span> , Middle Dutch&nbsp; <span class="foreign notranslate">wasscen</span> , Dutch&nbsp; <span class="foreign notranslate">wassen</span> , German&nbsp; <span class="foreign notranslate">waschen</span> ), from PIE root&nbsp; <a class="crossreference notranslate" title="Etymology, meaning and definition of *wed- " href="https://www.etymonline.com/word/*wed-#etymonline_v_52591" rel="nofollow" > *wed- </a> &nbsp;(1) "water; wet." Related:&nbsp; <span class="foreign notranslate">Washed</span> ;&nbsp; <a class="crossreference notranslate" title="Etymology, meaning and definition of washing " href="https://www.etymonline.com/word/washing" > washing </a> . </p> <p> Used mainly of clothes in Old English (the principal verb for washing the body, dishes, etc. being&nbsp; <span class="foreign notranslate">&thorn;wean</span> ). Old French&nbsp; <span class="foreign notranslate">gaschier</span> &nbsp;"to <strong>stain, soil; soak, wash</strong> " (Modern French&nbsp; <span class="foreign notranslate">g&acirc;cher</span> ) is from Frankish&nbsp; <span class="foreign notranslate">*waskan</span> , from the same Germanic source. Italian&nbsp; <span class="foreign notranslate">guazzare</span> &nbsp;also is a Germanic loan-word. To&nbsp; <span class="foreign notranslate">wash (one's) hands of</span> &nbsp;something is 1550s, from Pilate in Matthew xxvii.24. To&nbsp; <span class="foreign notranslate">wash up</span> &nbsp;"clean utensils after a meal" is from 1751.&nbsp; <span class="foreign notranslate">Washed up</span> "no longer effective" is 1923, theater slang, from notion of washing up at the end of a job. </p> </section> </div>`;

    // prettier.format(htmlContent, {
    prettier.format(jsonData.theCode, {
        parser: 'html',
        tabWidth: 2, // 设置缩进宽度
        htmlWhitespaceSensitivity: 'ignore' // 忽略HTML标签之间的空格
    }).then((formmatedHtml)=>{
        res.end(formmatedHtml);
    })
});


router.post('/querySpecified', function (req, res, next) {

    const jsonData = req.body;
    // console.log("requestData", jsonData);

    (async () => {
            const findResult = await markedFetchYoudaoLijuMainMapEntryCollectionDAO.theCollection.find({_id:new ObjectId(jsonData._id)}).sort({version: -1});
            let theResult;
            for await (const doc of findResult) {
                theResult = doc;
            }
            return theResult;
        }
    )().then(result => {
        res.end(JSON.stringify(result));
    });

    // res.send('respond with a resource');
});

router.get('/testQueryAllSavedList', function (req, res, next) {
    const jsonData = req.body;
    // console.log("requestData", jsonData);

    (async () => {
            let aggregated = markedFetchYoudaoLijuMainMapEntryCollectionDAO.theCollection.aggregate(
                [
                    { $match: { fetchKeyWordsRaw: 'flee//v.' } },
                    {
                        $lookup: {
                            from: 'markedFetchYoudaoLijuMainMapEntry',
                            localField: 'modifyBaseOn',
                            foreignField: '_id',
                            as: 'baseOn_mapping'
                        }
                    },
                    {
                        $set: {
                            baseOnFetchInfo: {
                                $first: '$baseOn_mapping'
                            }
                        }
                    },
                    {
                        $unset: [
                            'baseOnFetchInfo.resultLijuArr',
                            'modifyBaseOn',
                            'baseOn_mapping',
                            'baseOnFetchInfo.modifyBaseOn'
                        ]
                    },
                    {
                        $project: {
                            _id: 1,
                            fetchKeyWordsRaw: 1,
                            version: 1,
                            baseOnFetchInfo: 1
                        }
                    }
                ],
                { maxTimeMS: 60000, allowDiskUse: true }
            );

            console.log(aggregated);

            return 1;
        }
    )().then(result => {
        res.end(JSON.stringify(result));
    });
    // res.send('respond with a resource test1');
});

router.get('/querySavedLatestList', function (req, res, next) {
    // const jsonData = req.body;
    // console.log("requestData", jsonData);

    (async () => {
            return await latestMarkedVersionsDao.theCollection.find().toArray();
        }
    )().then(result => {
        res.end(JSON.stringify(result));
    });
    // res.send('respond with a resource test1');
});

router.get('/queryAllSavedList', function (req, res, next) {
    const jsonData = req.body;
    // console.log("requestData", jsonData);

    (async () => {
            let aggregated = await markedFetchYoudaoLijuMainMapEntryCollectionDAO.theCollection.aggregate(
                [
                    {
                        $lookup: {
                            from: 'markedFetchYoudaoLijuMainMapEntry',
                            localField: 'modifyBaseOn',
                            foreignField: '_id',
                            as: 'baseOn_mapping'
                        }
                    },
                    {
                        $set: {
                            baseOnFetchInfo: {
                                $first: '$baseOn_mapping'
                            }
                        }
                    },
                    {
                        $unset: [
                            'baseOnFetchInfo.resultLijuArr',
                            'modifyBaseOn',
                            'baseOn_mapping',
                            'resultLijuArr'
                        ]
                    },
                    {
                        $sort: { fetchKeyWordsRaw: 1, version: -1 }
                    }
                ],
                { maxTimeMS: 60000, allowDiskUse: true }
            );

            return await aggregated.toArray();
        }
    )().then(result => {
        res.end(JSON.stringify(result));
    });
    // res.send('respond with a resource test1');
});

router.post('/saveMarkedFetchYoudaoLijuMainMapEntry', function (req, res, next) {
    // res.send('respond with a resource test2');

    // {"fetchKeyWordsRaw":"flee//v.1"}

    const jsonData = req.body;
    // console.log("requestData", jsonData);

    (async () => {
            const findResult = await markedFetchYoudaoLijuMainMapEntryCollectionDAO.theCollection.find({fetchKeyWordsRaw: jsonData.fetchKeyWordsRaw}).sort({version: -1}).limit(1).project({
                _id: 0,
                version: 1
            });

            let maxVersion;
            for await (const doc of findResult) {
                maxVersion = doc.version;
            }
            // console.log('result =>', result);
            if (!maxVersion) {
                jsonData.version = 1;
                delete(jsonData.modifyBaseOn)
            } else {
                jsonData.version = maxVersion + 1;
            }

            if(jsonData.modifyBaseOn){
                jsonData.modifyBaseOn = new ObjectId(jsonData.modifyBaseOn?._id);
            }

            markedFetchYoudaoLijuMainMapEntryCollectionDAO.theCollection.insertOne(jsonData);

            return maxVersion;
        }
    )().then(result => {
        res.end("success");
    });
});

module.exports = router;
